﻿using System;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Storytelling.Negocio;
using Storytelling.Utils;
using Storytelling.Entidades;
using System.Security.Principal;
using System.Collections.Generic;

namespace Storytelling
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        private Thread thread;

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            Servicos.Usuario.SistemaSemAdministrador();

            Application["Chat"] = new Queue<KeyValuePair<long, Notificacao>>();

            thread = new Thread(RemoverVelhaNotificacao);
            thread.Start();
        }

        private void RemoverVelhaNotificacao()
        {
            Thread.Sleep(60000);

            Queue<KeyValuePair<long, Notificacao>> queue = Application["Chat"]
                as Queue<KeyValuePair<long, Notificacao>>;

            if (queue != null && queue.Count > 10)
            {
                queue.Dequeue();
            }

            thread = new Thread(RemoverVelhaNotificacao);
            thread.Start();
        }

        protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpCookie httpCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (httpCookie != null)
            {
                FormsAuthenticationTicket formsAuthenticationTicket = FormsAuthentication.Decrypt(httpCookie.Value);

                Context.User = new GenericPrincipal(new GenericIdentity(formsAuthenticationTicket.Name), 
                    formsAuthenticationTicket.UserData.Split(new Char[] { '|' }));
                Thread.CurrentPrincipal = Context.User;
            }
        }
    }
}